<?php

namespace common\logics;

use Yii;
use common\helpers\Url;
use common\helpers\ArrayHelper;

/**
 * 地址围栏模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class SiteMapLogic extends \common\models\WebviewMap {

    private $_data = [];

    public function bindParams($data) {
        $this->_data = (array) $data;
    }

    public function getData() {
        $params = $this->getFormatParams();
        $data = ArrayHelper::merge($params, $this->_data);
        return !empty($data) ? $data : null;
    }

    public function filterPath() {
        $path = $this->path;
        return str_replace([
            '{', '}'
        ], [
            ':', ''
        ], $path);
    }

    public function fields() {
        $fields = parent::fields();
        if (YII_ENV_DEV) {
            $fields['name'] = function() {
                return $this->filterPath();
            };
        }
        return $fields;
    }

    /**
     * 获取路由地址
     * @param integer|string $id
     * @param array $data
     * @return array
     */
    public static function findByData($id, array $data = []) {
        $condition = [];
        if (is_numeric($id)) {
            $condition['id'] = $id;
        } elseif (is_string($id)) {
            $condition['path'] = $id;
        } else {
            $condition = [
                'or',
                'id' => $id,
                'path' => $id,
            ];
        }
        $model = static::find()->active()->andWhere($condition)->one();
        if (!$model) {
            return null;
        }
        $model->bindParams($data);
        return $model;
    }

}
